/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.weibo.sina;

//import com.android.common.Search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.androidexamples.OAuthConstant;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.weibo.db.HomeTable;
import com.weibo.view.DragLayer;
import com.weibo.view.StatusCursorAdapter;
import com.weibo.view.StatusCursorAdapter.StatusObj;
import com.weibo.view.Workspace;

/**
 * Default launcher application.
 */
public final class TimeLineView extends Activity implements OnItemClickListener {
	static final String TAG = "TimeLineView";

	private Workspace mWorkspace;
	private ImageView mPreviousView;
	private ImageView mNextView;
	private List<Status> mTimeLine;
	private ListView mTimelineView;
	private Timer mTimer;
	// private StatusAdapter mAdapter;
	private StatusCursorAdapter mAdapter;
	private EditText mUpdate_edit;
	private HashMap<Long, Long> mMessageId;
	private static final int UPDATELIST = 0x00;
	private static final int UPDATEPROGRESSBAR = 0x01;
	private static final int HIDEBOTTOMTOOLBAR = 0x02;
	
	private static final int EXIT_DIALOG = 0x00;
	
	private boolean mIsGetBottom = false;
	private View mUpdateView;
	private static int mUpdatePage = 1;
	private ProgressBar mProgressbar;
	private static final int PROBARMAX = 100;
	private boolean mIsUpdating = false;
	private LinearLayout mBottomToolbar;

	private StatusObj mObj;
	private boolean mIs_Rt;
	private final Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATELIST:
				// Log.e(TAG, "update list ");
				if (mAdapter != null)
					mAdapter.notifyDataSetChanged();
				if (mTimelineView != null)
					mTimelineView.invalidate();
				break;
			case UPDATEPROGRESSBAR:
				Log.e(TAG, "mProgressbar.setProgress =" + msg.arg1);
				if (msg.arg1 > 0)
					mProgressbar.setVisibility(View.VISIBLE);
				mProgressbar.setProgress(msg.arg1);
				if (msg.arg1 == PROBARMAX)
					mProgressbar.setVisibility(View.INVISIBLE);
				break;
			case HIDEBOTTOMTOOLBAR:
				mBottomToolbar.startAnimation(AnimationUtils.loadAnimation(TimeLineView.this, R.anim.bottom_toolbar_out));
				mBottomToolbar.setVisibility(View.INVISIBLE);
				// if(mBottomToolbar.getVisibility()==View.VISIBLE){
				// mBottomToolbar.setVisibility(View.INVISIBLE);
				// }else{
				// mBottomToolbar.setVisibility(View.VISIBLE);
				// }
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.launcher);
		mMessageId = new HashMap<Long, Long>(30);

		mTimeLine = new ArrayList<Status>();
		DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer);
		mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
		mWorkspace.mLauncher = this;
		final Workspace workspace = mWorkspace;
		workspace.setHapticFeedbackEnabled(false);
		mProgressbar = (ProgressBar) dragLayer.findViewById(R.id.progressbar);
		mProgressbar.setMax(PROBARMAX);
		mProgressbar.setProgress(0);
		mBottomToolbar = (LinearLayout) findViewById(R.id.bottom_toolbar);
		setupPages();
	}

	private void setupPages() {

		// mHandler.post(new UpdateTLThread());
		getContentResolver().delete(HomeTable.CONTENT_URI, null, null);
		Cursor cursor = managedQuery(HomeTable.CONTENT_URI, null, null, null, HomeTable.DEFAULT_SORT_ORDER);
		mAdapter = new StatusCursorAdapter(TimeLineView.this, cursor, R.layout.status_view);
		View view = findViewById(mWorkspace.getPage(mWorkspace.getCurrentScreen()));
		mTimelineView = (ListView) view.findViewById(R.id.timeline);
		mTimelineView.setAdapter(mAdapter);
		mTimelineView.setOnItemClickListener(this);
		new UpdateTLThread().start();
	}

	/*
	 * private void getTimeLine(int page) { //Log.e(TAG, "get page =" + page);
	 * Weibo weibo = OAuthConstant.getInstance().getWeibo();
	 * weibo.setToken(OAuthConstant.getInstance().getToken(),
	 * OAuthConstant.getInstance().getTokenSecret()); //Log.e(TAG, "User id =" +
	 * weibo.getUserId()); try { mTimeLine.clear();
	 * mTimeLine.addAll(weibo.getFriendsTimeline(new Paging(page))); for(int i
	 * =0;i<mTimeLine.size();i++){ //Log.e(TAG, mTimeLine.get(i).toString()); }
	 * mHandler.obtainMessage(UPDATELIST).sendToTarget(); } catch
	 * (WeiboException e) { e.printStackTrace(); } }
	 */

	private void getTimeLine(int page) {
		// Log.e(TAG, "get page =" + page);

		mHandler.obtainMessage(UPDATEPROGRESSBAR, 10, 0).sendToTarget();
		Weibo weibo = OAuthConstant.getInstance().getWeibo();
		weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant.getInstance().getTokenSecret());
		mHandler.obtainMessage(UPDATEPROGRESSBAR, 20, 0).sendToTarget();
		// Log.e(TAG, "User id =" + weibo.getUserId());
		// getContentResolver().delete(HomeTable.CONTENT_URI, null, null);
		try {
			List<Status> timeLine = weibo.getFriendsTimeline(new Paging(page));
			mHandler.obtainMessage(UPDATEPROGRESSBAR, 70, 0).sendToTarget();
			int progress = 70;
			for (int i = 0; i < timeLine.size(); i++) {
				Status data = timeLine.get(i);
				mHandler.obtainMessage(UPDATEPROGRESSBAR, progress++, 0).sendToTarget();
				Long id = data.getId();
				if (mMessageId.containsKey(id)) {
					// Log.e(TAG, "mMessageId.containsKey id =" + data.getId());
					continue;
				} else {
					// Log.e(TAG, "mMessageId not containsKey id =" +
					// data.getId());
					ContentValues values = new ContentValues();
					values.put(HomeTable._ID, id);
					mMessageId.put(id, data.getUser().getId());
					values.put(HomeTable.UID, data.getUser().getId());
					values.put(HomeTable.FAVID, data.getUser().getFavouritesCount());
					values.put(HomeTable.NICK, data.getUser().getName());
					values.put(HomeTable.PORTRAIT, data.getUser().getProfileImageURL().toString());
					values.put(HomeTable.VIP, data.getUser().isVerified() ? 1 : 0);
					values.put(HomeTable.CONTENT, data.getText());
					if (data.getRetweeted_status() != null) {
						values.put(HomeTable.RTROOTUID, data.getRetweeted_status().getUser().getId());
						values.put(HomeTable.RTROOTID, data.getRetweeted_status().getId());
						values.put(HomeTable.RTROOTNICK, data.getRetweeted_status().getUser().getName());
						values.put(HomeTable.RTROOTVIP, data.getRetweeted_status().getUser().isVerified() ? 1 : 0);
						values.put(HomeTable.RTREASON, data.getRetweeted_status().getText());
						values.put(HomeTable.RTROOTVIP, data.getRetweeted_status().getUser().isVerified() ? 1 : 0);
						values.put(HomeTable.PIC, data.getRetweeted_status().getThumbnail_pic());
						values.put(HomeTable.OPIC, data.getRetweeted_status().getOriginal_pic());
					} else {
						values.put(HomeTable.PIC, data.getThumbnail_pic());
						values.put(HomeTable.OPIC, data.getOriginal_pic());
					}
					values.put(HomeTable.TIME, data.getCreatedAt().getTime());
					String source = Html.fromHtml(data.getSource()).toString();
					Html.fromHtml(data.getSource()).toString();
					values.put(HomeTable.SRC, source);
					values.put(HomeTable.LONGITUDE, data.getLongitude());
					values.put(HomeTable.LATITUDE, data.getLatitude());
					try {
						getContentResolver().insert(HomeTable.CONTENT_URI, values);
					} catch (SQLiteConstraintException e) {
						e.printStackTrace();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
			mHandler.obtainMessage(UPDATELIST).sendToTarget();
			mHandler.obtainMessage(UPDATEPROGRESSBAR, PROBARMAX, 0).sendToTarget();

		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	class UpdateTLThread extends Thread {

		@Override
		public void run() {
			String oauth_verifier;
			if (Authorize.ISAUTHORED) {
				SharedPreferences user = getSharedPreferences("oauth", 0);
				oauth_verifier = user.getString("oauth_verifier", "");
			} else {
				Uri uri = TimeLineView.this.getIntent().getData();
				oauth_verifier = uri.getQueryParameter("oauth_verifier");
				Log.e(TAG,uri.toString());
				
				SharedPreferences user = getSharedPreferences("oauth", 0);
				Editor editor = user.edit();
				editor.putString("oauth_verifier", oauth_verifier);
				editor.commit();
				Authorize.ISAUTHORED = true;
				try {
					Log.e(TAG,"oauth_verifier="+oauth_verifier);
					RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();
					AccessToken accessToken = requestToken.getAccessToken(oauth_verifier);
					OAuthConstant.getInstance().setAccessToken(accessToken);
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}
			getTimeLine(1);

			mTimelineView.setOnScrollListener(new OnScrollListener() {

				public void onScrollStateChanged(AbsListView view, int scrollState) {
					switch (scrollState) {
					case OnScrollListener.SCROLL_STATE_IDLE:
						// //Log.e(TAG, "已经停止：SCROLL_STATE_IDLE");
						break;
					case OnScrollListener.SCROLL_STATE_FLING:
						// //Log.e(TAG, "正在滚动：SCROLL_STATE_TOUCH_SCROLL");
						break;
					case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
						// //Log.e(TAG, "开始滚动：SCROLL_STATE_FLING");
						if (mIsGetBottom && (!mIsUpdating)) {
							new TimeLineThread(++mUpdatePage).start();
						}
						break;
					}

				}

				public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
					// //Log.e(TAG, "onScrollStateChanged firstVisibleItem= " +
					// firstVisibleItem + " visibleItemCount = " +
					// visibleItemCount
					// + " totalItemCount=" + totalItemCount);
					if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
						mIsGetBottom = true;
					} else {
						mIsGetBottom = false;
					}
				}
			});
			super.run();
		}

	}

	public void handleBtn(View view) {
		switch (view.getId()) {
		case R.id.refresh_btn:
			if (!mIsUpdating) {
				new TimeLineThread(1).start();
			}
			break;
		case R.id.home_btn:
			startActivity(new Intent(this, Face.class));
			break;
		case R.id.tweet_btn:
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			AlertDialog update=builder.create();
//			View root = getLayoutInflater().inflate(R.layout.post_message, null);
//			update.setView(root);
//			//update.addContentView(root, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//			update.show();
			startActivity(new Intent(this,PostMassage.class));
			overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
			break;
		}
	}

	class TimeLineThread extends Thread {
		private int mPage;

		public TimeLineThread(int page) {
			mPage = page;
		}

		@Override
		public void run() {
			if (!mIsUpdating) {
				mIsUpdating = true;
				getTimeLine(mPage);
			}
			mIsUpdating = false;
			super.run();
		}

	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Log.e(TAG, "item position = " + position);

	}

	public void onItemClick(View view) {
		Log.e(TAG, "item position = " + view.getId());
		if(view.getId()==R.id.rt_reason)
			mIs_Rt=true;
		else
			mIs_Rt=false;
		
		mObj = (StatusObj) view.getTag();

		if (mBottomToolbar.getVisibility() == View.INVISIBLE) {
			mBottomToolbar.setVisibility(View.VISIBLE);
			mBottomToolbar.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_toolbar_in));
		}
		TimerTask mTask = new TimerTask() {
			public void run() {
				mHandler.obtainMessage(HIDEBOTTOMTOOLBAR).sendToTarget();
			}
		};
		if (mTimer != null) {
			mTimer.cancel();
			mTimer.purge();
			mTimer = new Timer(true);
			mTimer.schedule(mTask, 4000);
		} else {
			mTimer = new Timer(true);
			mTimer.schedule(mTask, 4000);
		}
	}

	public void onBottomToolBarClick(View view) {
		Weibo weibo = OAuthConstant.getInstance().getWeibo();

		if(mObj!=null){
		Log.e(TAG, "id = " + mObj);
		switch (view.getId()) {
		case R.id.swipe_fav:
			try {
				mHandler.obtainMessage(HIDEBOTTOMTOOLBAR).sendToTarget();
				weibo.createFavorite(mObj.getId());
				//View toastRoot = getLayoutInflater().inflate(R.layout.tips_view, null);
				Toast.makeText(this.getBaseContext(), getString(R.string.tips_fav_ok), Toast.LENGTH_LONG).show();
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.swipe_reply:
			mHandler.obtainMessage(HIDEBOTTOMTOOLBAR).sendToTarget();
			Intent intent = new Intent(getBaseContext(),ReplyMessage.class);
			if(mIs_Rt){
				intent.putExtra("id", mObj.getRt_id());
				intent.putExtra("name", mObj.getRt_nick());
				intent.putExtra("content", mObj.getRt_reason());
				Log.e(TAG,"id="+mObj.getRt_id()+" name="+mObj.getRt_nick()+" content="+mObj.getRt_reason());
			}else{
				intent.putExtra("id", mObj.getId());
				intent.putExtra("name", mObj.getNick());
				intent.putExtra("content", mObj.getContent());
				Log.e(TAG,"id="+mObj.getId()+" name="+mObj.getNick()+" content="+mObj.getContent());
			}
			startActivity(intent);
			overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
			break;
		case R.id.swipe_retweet:
			mHandler.obtainMessage(HIDEBOTTOMTOOLBAR).sendToTarget();
			Intent retweet = new Intent(getBaseContext(),RetweetMessage.class);
			if(mIs_Rt){
				retweet.putExtra("id", mObj.getRt_id());
				retweet.putExtra("name", mObj.getRt_nick());
				retweet.putExtra("content", mObj.getRt_reason());
				Log.e(TAG,"id="+mObj.getRt_id()+" name="+mObj.getRt_nick()+" content="+mObj.getRt_reason());
			}else{
				retweet.putExtra("id", mObj.getId());
				retweet.putExtra("name", mObj.getNick());
				retweet.putExtra("content", mObj.getContent());
				Log.e(TAG,"id="+mObj.getId()+" name="+mObj.getNick()+" content="+mObj.getContent());
			}
			startActivity(retweet);
			overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
			break;
		}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			showDialog(EXIT_DIALOG);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected Dialog onCreateDialog(int id, Bundle args) {
		switch(id){
		case EXIT_DIALOG:
			return new AlertDialog.Builder(this).setMessage(R.string.sure_exit).setPositiveButton(R.string.yes, new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					finish();
					
				}
			}).setNegativeButton(R.string.no, new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dismissDialog(EXIT_DIALOG);
				}
			}).create();
		}
		return null;
	}
	
	
	
	
}
